package com.pocket.demo.core.security.authorize;

import com.pocket.demo.base.consts.SecurityConst;
import com.pocket.demo.business.service.MenuService;
import com.pocket.demo.core.security.PocketUser;
import jakarta.annotation.Resource;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;
import org.springframework.util.AntPathMatcher;

import java.util.Collection;
import java.util.List;

/**
 * 【demo-SpringSecurity-7.1】
 * @author zhaozhile
 */
//@Component
public class PocketFilterInvocationSecurityMetadataSource implements FilterInvocationSecurityMetadataSource {

    @Resource public MenuService menuService;
    AntPathMatcher pathMatcher = new AntPathMatcher();

    @Override
    public Collection<ConfigAttribute> getAttributes(Object object) throws IllegalArgumentException {
        UsernamePasswordAuthenticationToken authenticationToken = (UsernamePasswordAuthenticationToken) SecurityContextHolder.getContext().getAuthentication();
        PocketUser loginUser = (PocketUser) authenticationToken.getPrincipal();
        String url = ((FilterInvocation)object).getRequestUrl();

        // TODO 缓存系统所有资源和角色的对应关系
        // TODO 判断访问当前URL资源需要那些角色权限
        for(String sourceUrl : loginUser.getPermissions()){
            if(pathMatcher.match(sourceUrl, url)){
                return SecurityConfig.createList(sourceUrl);
            }
        }
        // 匹配不到的默认返回
        return SecurityConfig.createList(SecurityConst.ROLE_NONE);
    }

    @Override
    public Collection<ConfigAttribute> getAllConfigAttributes() {
        return List.of();
    }

    @Override
    public boolean supports(Class<?> clazz) {
        return true;
    }
}
